<?php

class invite {

	private $sourceTemplate;
	private $salt = "XC_75M3";
	private $hash;
	
	public static function validate($username, $hash){
		
	}
	
	public function __construct(template $tpl){
		$this->sourceTemplate = $tpl;
	}
	
	public function generateMessage(user &$userObj, $username, $institutionName, $type){		
		return sprintf($this->sourceTemplate->get(), $userObj->getFirstName() . " " . $userObj->getLastName(), $institutionName, SYS_BASEURL . SYS_RUNLANG . "/home" );
	}


	public function generateActivationMessage($email, $type){
		$hash = $this->hash($email, $type);
		$this->hash = $hash;
		return sprintf($this->sourceTemplate->get(), $this->generateActivationLink($hash) );
	}

	private function generateActivationLink($hash){
		return SYS_BASEURL . SYS_RUNLANG . "/activate?i=$hash";
	}

	public function hash($u, $act = ''){
		return md5( time() . $u . $act . $this->salt );
	}
	
	public function getHash(){
		return $this->hash;
	}
	
	public static function match_hash($hash){
		$dbCon = db::singleton();
		
		$res = $dbCon->oneRow("SELECT type, email, institution_instID, state FROM " . SYS_DB_DBNAME . ".invitations WHERE actHash='" . $dbCon->real_escape_string($hash) . "';");
		return $res;
	}
	
	public static function delete_invite($hash){
		$dbCon = db::singleton();
		
		$dbCon->single("DELETE FROM " . SYS_DB_DBNAME . ".invitations WHERE actHash='" . $dbCon->real_escape_string($hash) . "';");
	}
	
	public function generateResetEmail($email){
		$dbCon = db::singleton();
		
		$hash = $this->hash($email, 'resetPassword');
		
		$dbCon->single("INSERT INTO " . SYS_DB_DBNAME . ".invitations (type, email, actHash, state) VALUES('reset', '" . $dbCon->real_escape_string($email) . "', '" . $hash . "', 1)");
	
		return sprintf($this->sourceTemplate->get(), SYS_BASEURL . SYS_RUNLANG . "/reset?i=$hash" );
	}
	
	public static function activateAccount($email, $hash){
		// Step 1: Delete from invitations
		// Step 2: flip 'active' to 1 in users table for corresponding email address
		
		$dbCon = db::singleton();
		
		// Switch on transactions
		$dbCon->startTransaction();
		
		try {
			if( is_null($email) == false && is_null($hash) == false ){
				$dbCon->single("DELETE FROM " . SYS_DB_DBNAME . ".invitations WHERE actHash='" . $dbCon->real_escape_string($hash) . "' AND email='" . $dbCon->real_escape_string($email) . "'");
				
				if($dbCon->affected_rows == 1){
					$dbCon->single("UPDATE " . SYS_DB_DBNAME . ".user SET active=1 WHERE emailAddress='" . $dbCon->real_escape_string($email) . "'");
				} else {
					$dbCon->rollback();
					return false;
				}
				$dbCon->commit();
				return true;
			} else {
				return false;
			}
			
			return false;
		} catch (Exception $e){
			$dbCon->rollback();
			return false;
		}
		
	}

}

?>